import React, { Component } from 'react';
import {
	StyleSheet, Text, View, Image,
	TouchableOpacity, FlatList, ActivityIndicator, PixelRatio
} from "react-native";
import { API, API_GENERATE } from '../../../config/api';
import ValidateDataUtil from '../../../utils/ValidateDataUtil';
import HTTP from '../../../utils/http';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { Common } from '../../../component/common/Common';
import { cStyles } from '../storeStyle.js';

const scale = GLOBAL.SCALE;
const statusList = [{
	key: 'PASS',
	text: '待盘点'
}, {
	key: 'RUNNING',
	text: '盘点中'
}, {
	key: 'COMPLETE',
	text: '已盘点'
}];

const arrow = require('../../../imgs/arrowBlue.png');
let pageNo = 1;//当前第几页
let totalPage = 1;//总的页数
let recordCount = 0;//总的数量
const requestObj = {
	pageNo: 1,
	pageSize: 10,
	status: 'PASS',
};

export class StockTackingPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '盘点',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: {
				elevation: 0,
				backgroundColor: style.color.themeColor,
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props);
		this.state = {
			pageStatus: {
				status: 'loading'
			},
			curStockStatus: 'PASS',
			loaded: true,
			dataSource: [],
			showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
		};
		requestObj.status = 'PASS';
		this._fetchStocktakingInfoAsync = this._fetchStocktakingInfoAsync.bind(this);
		this._renderItem = this._renderItem.bind(this);
	}

	/**
 * @private
 */
	async _fetchStocktakingInfoAsync (pageNo) {
		requestObj.pageNo = pageNo;
		const responseData = await HTTP.POST(API_GENERATE(API.GET_STOCKPLAN_LIST), requestObj);

		if (!responseData) {

			this.setState({
				loaded: false,
			});

		} else {
			const { rows } = responseData;
			recordCount = responseData.recordCount;
			totalPage = responseData.totalPage;

			let foot = 0;
			if (pageNo >= totalPage) {
				foot = 1;//listView底部显示没有更多数据了
			}
			this.setState({
				dataSource: this.state.dataSource.concat(rows),
				loaded: false,
				showFoot: foot
			});
		}
	}

	async componentWillMount () {
		await this._fetchStocktakingInfoAsync(pageNo);
	}

	async componentDidMount () {

	}

	async _didPressStatusTab (status) {
		pageNo = 1;
		requestObj.pageNo = pageNo;
		requestObj.status = status;
		this.setState({
			curStockStatus: status,
			loaded: true,
			dataSource: [],
		});
		this._fetchStocktakingInfoAsync(pageNo)
	}

	render () {
		const lastStatusListIndex = statusList.length - 1;
		const topTabViews = statusList.map((item, index) => {
			const { key, text } = item;
			const { curStockStatus } = this.state;
			const colText = (index != lastStatusListIndex) ? '|' : '';
			const topTabViewStyle = (key == curStockStatus) ? styles.topTabViewCur : null;
			const topTabTextStyle = (key == curStockStatus) ? { color: style.color.themeColor, } : null;
			return (
				<TouchableOpacity onPress={this._didPressStatusTab.bind(this, key)} activeOpacity={0.5} style={[styles.topTabView, topTabViewStyle]} key={key}>
					<Text></Text>
					<Text style={[styles.topTabText, topTabTextStyle]}>{text}</Text>
					<Text style={{ color: '#ccc' }}>{colText}</Text>
				</TouchableOpacity>
			);
		});

		const renderDataView = this.renderData();
		return (
			<View style={styles.container}>

				<View style={styles.topTabCell}>
					{topTabViews}
				</View>
				<View style={styles.headTop}>
					{renderDataView}
				</View>
			</View>
		)
	}

	/* 渲染列表 */
	renderData () {
		if (this.state.loaded) {
			// return null;
			return (
				<PageStatusIndex status={'loading'} />);
		} else {
			if (this.state.dataSource.length) {
				return (
					<FlatList
						data={this.state.dataSource}
						renderItem={this._renderItem}
						ListFooterComponent={this._renderFooter.bind(this)}
						onEndReachedThreshold={1}
						onEndReached={this._onEndReached.bind(this)}
						onRefresh={this._onRefresh.bind(this)}
						refreshing={false}
						style={styles.flatList}
					/>
				);
			} else {
				return (
					<PageStatusIndex status={'empty'} />);
				// return null; emptyText={'没有查找到满足条件的数据'}
			}
		}

	}

	_renderItem (StockTacking) {
		const { checkSubject, inventoryStandBookVOS, planDate, planId, status, warehouseId, warehouseName, checkBeginTime, checkEndTime } = StockTacking.item;
		const { curStockStatus } = this.state;
		let tockTackingView = null;
		const { navigate } = this.props.navigation;

		if (curStockStatus == 'PASS') {
			tockTackingView = (
				<TouchableOpacity style={[styles.panel]} onPress={() => {
					navigate('StockDetailPage', {
						title: checkSubject,
						planId,
					});
				}} activeOpacity={0.5} >
					<View style={[styles.panelRow, styles.panelTop]}>
						<View style={styles.panelTopLeft}><Text style={cStyles.textBig}>{checkSubject}</Text></View>
						<View style={styles.panelTopRight}>
							<Text style={[cStyles.text, cStyles.textSuccess, { marginRight: 9 * scale, }]}>{status}</Text>
							<Image source={arrow} />
						</View>
					</View>
					<View style={styles.panelRow}><Text style={cStyles.text}>仓库名称：{warehouseName}</Text></View>
					<View style={styles.panelRow}><Text style={cStyles.text}>预定盘点日期：{this._getDateStr(planDate)}</Text></View>
				</TouchableOpacity>
			);
		} else if (curStockStatus == 'RUNNING') {
			tockTackingView = (
				<TouchableOpacity style={styles.panel} onPress={() => {
					navigate('StockEditPage', {
						title: checkSubject,
						planId,
					});
				}} activeOpacity={0.5} >
					<View style={[styles.panelRow, styles.panelTop]}>
						<View style={styles.panelTopLeft}><Text style={cStyles.textBig}>{checkSubject}</Text></View>
						<View style={styles.panelTopRight}>
							<Text style={[cStyles.text, cStyles.textSuccess, { marginRight: 9 * scale, }]}>{status}</Text>
							<Image source={arrow} style={''} />
						</View>
					</View>
					<View style={styles.panelRow}><Text style={cStyles.text}>仓库名称：{warehouseName}</Text></View>
					<View style={styles.panelRow}><Text style={cStyles.text}>开始盘点时间：{this._getTimeStr(checkBeginTime)} </Text></View>
				</TouchableOpacity>
			);
		} else if (curStockStatus == 'COMPLETE') {
			tockTackingView = (
				<TouchableOpacity style={[styles.panel]} onPress={() => {
					navigate('StockDetailCompletePage', {
						title: checkSubject,
						planId,
					});
				}} activeOpacity={0.5} >
					<View style={[styles.panelRow, styles.panelTop]}>
						<View style={styles.panelTopLeft}><Text style={cStyles.textBig}>{checkSubject}</Text></View>
						<View style={styles.panelTopRight}>
							<Text style={[cStyles.text, cStyles.textSuccess, { marginRight: 9 * scale, }]}>{status}</Text>
							<Image source={arrow} style={''} />
						</View>
					</View>
					<View style={styles.panelRow}><Text style={cStyles.text}>仓库名称：{warehouseName}</Text></View>
					<View style={styles.panelRow}><Text style={cStyles.text}>开始盘点时间：{this._getTimeStr(checkBeginTime)}</Text></View>
					<View style={styles.panelRow}><Text style={cStyles.text}>结束盘点时间：{this._getTimeStr(checkEndTime)} </Text></View>
				</TouchableOpacity>
			);
		}

		return (
			<View style={styles.panelCell} key={planId}>
				{tockTackingView}
			</View>);
	}

	/*下拉*/
	_onRefresh () {
		this.setState({
			dataSource: [],
			loaded: true,
		});
		pageNo = 1;
		requestObj.pageNo = pageNo;
		this._fetchStocktakingInfoAsync(pageNo);
	}

	/*上拉*/
	_onEndReached () {
		//如果是正在加载中或没有更多数据了，则返回
		if (this.state.showFoot != 0) {
			return;
		}
		//如果当前页大于或等于总页数，那就是到最后一页了，返回
		if ((pageNo != 1) && (pageNo >= totalPage)) {
			return;
		} else {
			pageNo++;
		}
		//底部显示正在加载更多数据
		this.setState({ showFoot: 2 });
		//获取数据
		this._fetchStocktakingInfoAsync(pageNo);
	}

	/*for FlatList的底部*/
	_renderFooter () {
		if (this.state.showFoot === 1) {
			return (
				<View style={{ height: 30, alignItems: 'center', justifyContent: 'flex-start', }}>
					<Text style={styles.noMoreText}>
						没有更多数据了
								</Text>
				</View>
			);
		} else if (this.state.showFoot === 2) {
			return (
				<View style={styles.footer}>
					<ActivityIndicator />
					<Text>正在加载更多数据...</Text>
				</View>
			);
		} else if (this.state.showFoot === 0) {
			const curRecordCount = pageNo * requestObj.pageSize;
			return (
				<PageStatusIndex status="bottom" recordCount={recordCount} nowList={curRecordCount} />
			);
		}
	}

	_getTimeStr (str) {
		if (!ValidateDataUtil.isEmpty(str)) {
			const currDate = new Date(str.replace(/-/g, '/'));
			var y = currDate.getFullYear(),
				m = currDate.getMonth() + 1,
				d = currDate.getDate(),
				h = currDate.getHours(),
				mi = currDate.getMinutes();
			let dateStr = "";
			dateStr += y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + (h < 10 ? "0" + h : h) + ":" + (mi < 10 ? "0" + mi : mi);
			return dateStr;
		} else {
			return null;
		}
	}

	_getDateStr (str) {
		if (!ValidateDataUtil.isEmpty(str)) {
			const currDate = (typeof str == 'string') ? new Date(str.replace(/-/g, '/')) : str;
			var y = currDate.getFullYear(),
				m = currDate.getMonth() + 1,
				d = currDate.getDate();
			var dateStr = "";
			dateStr += y + "." + (m < 10 ? "0" + m : m) + "." + (d < 10 ? "0" + d : d);
			return dateStr;
		} else {
			return '';
		}
	}

}

const styles = StyleSheet.create({
	flatList: {
		paddingTop: 12 * scale,
	},
	footer: {
		flexDirection: 'row',
		height: 24,
		justifyContent: 'center',
		alignItems: 'center',
		marginBottom: 10,
	},
	noMoreText: {
		color: '#999999',
		fontSize: 14 * scale,
		marginTop: 5 * scale,
		marginBottom: 5 * scale,
	},
	panelCell: {
		width: 375 * scale,
		alignItems: 'center',
	},
	panel: {
		width: 351 * scale,
		marginBottom: 12 * scale,
		paddingTop: 12 * scale,
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
		backgroundColor: '#fff',
		borderRadius: 8,
	},
	panelRow: {
		marginBottom: 12 * scale,
	},
	panelTop: {
		flexDirection: 'row',
	},
	panelTopLeft: {
		paddingLeft: 10 * scale,
		flexDirection: 'row',
		flex: 3,
		borderLeftColor: style.color.themeColor,
		borderLeftWidth: 2,
	},
	panelTopRight: {
		flexDirection: 'row',
		flex: 1,
		alignItems: 'center',
		justifyContent: 'flex-end'
	},
	container: {
		flex: 1,
		backgroundColor: '#F5F5F5',
	},
	topTabCell: {
		width: 375 * scale,
		height: 50 * scale,
		flexDirection: 'row',
		backgroundColor: '#fff',
	},
	topTabView: {
		flex: 1,
		justifyContent: 'space-between',
		alignItems: 'center',
		flexDirection: 'row',
		borderBottomColor: '#fff',
		borderBottomWidth: 3 / PixelRatio.get(),
	},
	topTabViewCur: {
		borderBottomColor: style.color.themeColor,
	},
	topTabText: {
		fontSize: 14 * scale,
		color: '#8B8B8B'
	},
	headTop: { marginTop: 12 * scale, flex: 1 }
});